package com.koko.controller;

import com.koko.game.vo.GameViewListVO;
import com.koko.game.vo.GameViewVO;
import com.koko.result.Result;
import com.koko.service.GameViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/game")
public class GameViewController {
    @Autowired
    private GameViewService gameViewService;

    @GetMapping("/admin/viewlist")
    @Cacheable(value = "gameCache", key = "'gameViewList' + '_' + #gameId")
    public Result<GameViewListVO<GameViewVO>> getViewListByGameId(@RequestParam Long gameId) {
        GameViewListVO gameViewListVO = gameViewService.getGameViewWithIdByGameId(gameId);
        return Result.success(gameViewListVO);
    }

    @PostMapping("/admin/view/video")
    @CacheEvict(value = "gameCache", allEntries = true)
    public Result<String> uploadChunk(@RequestParam("gameId") Long gameId,
                                      @RequestParam("chunk") MultipartFile chunk,
                                      @RequestParam("index") Integer index,
                                      @RequestParam("totalChunks") Integer totalChunks,
                                      @RequestParam("fileName") String fileName) {
        gameViewService.uploadVideo(gameId, chunk, index, totalChunks, fileName);
        return Result.success();
    }

    @PostMapping("/admin/view/image")
    @CacheEvict(value = "gameCache", allEntries = true)
    public Result<String> imageUpload(@RequestParam("gameId") Long gameId,
                                      @RequestParam("image") MultipartFile imageFile) {
        gameViewService.uploadImage(gameId, imageFile);
        return Result.success();
    }

    @DeleteMapping("/admin/view")
    @CacheEvict(value = "gameCache", allEntries = true)
    public Result<String> deleteBatch(@RequestBody List<Long> ids) {
        gameViewService.deleteBatch(ids);
        return Result.success();
    }

}
